<?php
declare (strict_types = 1);

namespace app\model\mysql;

use think\Model;

class Category extends Model {

    protected $name = "category";

    protected $autoWriteTimestamp = true;

    protected $updateTime = "updated_time";

    protected $createTime = "created_time";

    protected $hidden = ["is_delete"];

    public static function checkUrlKey($urlKey = "", $currentId = 0) {

        return static::where("url_key", $urlKey)
            ->where("id", "<>",   $currentId)
            ->where("is_delete", "<>", 1)->find();
    }

    public function list($currentId = 0, $fields, $_where = []) {
        $where = [
            ["id", "<>", $currentId],
            ["is_delete", "=", 0],
        ];
        if (!empty($where)) {
            $where = array_merge($where, $_where);
        }
        return $this->where($where)
            ->field($fields)->select();
    }

    public function pageList($paginate, $where, $order, $fields) {
        if (empty($paginate)) {
            return [];
        }
        $model = $this;
        if (!empty($where)) {
            $model = $model->where($where);
        }
        if (!empty($order)) {
            $model = $model->order($order);
        }
        if (!empty($fields)) {
            $model = $model->field($fields);
        }
        return $model->paginate($paginate);
    }

    public function updateById($id = 0, $data = []) : bool {
        if ($id <= 0 || empty($data)) {
            return false;
        }
        $data["updated_time"] = date("Y-m-d H:i:s", time());
        return $this->where("id", $id)->save($data) ? true : false;
    }

    public function deleteById($id = 0, $operator = "") : bool {
        if ($id <= 0) {
            return true;
        }

        $data["updated_time"] = date("Y-m-d H:i:s", time());
        $data["is_delete"] = 1;
        $data["operate_user"] = $operator;
        return $this->where("id", $id)->save($data) ? true : false;
    }

    public function getCountListByPids($pidArr = []) : array {
        if (empty($pidArr)) {
            return [];
        }

        $where = [
            ["pid", "in", $pidArr],
            ["is_delete", "<>", 1]
        ];

        $result = $this->where($where)
            ->field("pid, count(id) as count")
            ->group("pid")
            ->select();
        return $result ? $result->toArray() : [];
    }

    public function getListByPid($pid = 0, $field = "id, name,  pid") : array {
        $where = [
            ["pid", "=", $pid],
            ["is_delete", "<>", 1]
        ];

        $result = $this->where($where)->field($field)->select();

        return $result ? $result->toArray() : [];
    }
}